"""
The history module contains helper classes to store the 
history of user events.
Writen By: Daniel Ortiz
"""

class HistoryBuffer(object):
    def __init__(self, size = 1000):
        self.size = size
        self.Variables()
        self.InitializeBuffer()
        
    def Variables(self):
        """Initialize the class wide variables"""
        self.buffer = []
        self.cur_index = -1
        self.stop_index = -1

    def InitializeBuffer(self):
        """Initialize the buffer: A buffer is a list of tuples.
        The tuples have the form...
        (pos, char, widget, callback)
        """
        for k in range(self.size):
            self.buffer.append((-1, -1, -1, None))
            
    def Log(self, pos, char, action, callback):
        """Save the last action in the circular buffer"""
        self.cur_index = (self.stop_index + 1) % self.size
        self.stop_index = self.cur_index
        self.buffer[self.cur_index] = (pos, char, action, callback)
        
    def Undo(self):
        """Call the widget to undo the previous action"""
        next_index = (self.cur_index -1) % self.size
        if next_index != self.stop_index  and self.buffer[self.cur_index][0] != -1:
            pos, char, action, callback = self.buffer[self.cur_index]
            if callable(callback):
                callback(pos, char, action, "UNDO")
            self.cur_index = (self.cur_index - 1) % self.size
        
    def Redo(self):
        """Call the widget to redo the previous action"""
        next_index = (self.cur_index + 1) % self.size
        if self.cur_index != self.stop_index and self.buffer[next_index][0] != -1:
            pos, char, action, callback = self.buffer[next_index]
            if callable(callback):
                callback(pos, char, action, "REDO")
            self.cur_index = (self.cur_index + 1) % self.size
    
            
            